package com.ruins.ping.consumer

import cn.hutool.core.date.DateUtil
import com.ruins.ping.PingApplication
import com.ruins.ping.vo.Log
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.test.context.ContextConfiguration
import spock.lang.Specification
import spock.lang.Unroll

@Unroll
@ContextConfiguration(classes = PingApplication.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class LogReceiverTest extends Specification {

    LogReceiver logReceiver
    MongoTemplate mongoTemplate = Mock(MongoTemplate)

    def setup() {
        logReceiver = new LogReceiver(mongoTemplate)
    }

    def "receiveLog should save log information to MongoDB"() {
        given:
        String message = '{"pid":"12345","logMessage":"Test log message"}'
        Log expectedLog = new Log()
        expectedLog.setPid("12345")
        expectedLog.setMessage("Test log message")
        expectedLog.setCreateTime(DateUtil.now())

        when:
        logReceiver.receiveLog(message)

        then:
        1 * mongoTemplate.save(_ as Log) >> { Log log ->
            log.getPid() == expectedLog.getPid()
            log.getMessage() == expectedLog.getMessage()
            log.getCreateTime() == expectedLog.getCreateTime()
        }
    }
}